import { useState } from 'react'
import {
  Form,
  Input,
  DatePicker,
  InputNumber,
  Button,
  message,
  Row,
  Col,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import {
  createDefaultWorkTimeRecord,
  validateWorkTimeData,
} from '../utils/dataParser'

const { TextArea } = Input

const AddWorkTime = ({ onAddWorkTime }) => {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)

  // 处理表单提交
  const handleSubmit = async (values) => {
    setLoading(true)
    try {
      // 格式化数据
      const workTimeRecord = {
        ...createDefaultWorkTimeRecord(),
        date: values.date.format('YYYY-MM-DD'),
        content: values.content,
        hours: values.hours || 0,
        remaining: values.remaining || 0,
        object: values.object || '',
        product: values.product || '',
        executor: values.executor || '',
        project: values.project || '',
      }

      // 验证数据
      if (!validateWorkTimeData(workTimeRecord)) {
        message.error('数据验证失败，请检查必填项')
        return
      }

      // 调用回调函数
      onAddWorkTime(workTimeRecord)

      // 重置表单
      form.resetFields()
      message.success('工时记录添加成功')
    } catch (error) {
      console.error('添加工时记录失败:', error)
      message.error('添加失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  // 表单验证规则
  const validateRules = {
    date: [{ required: true, message: '请选择日期' }],
    content: [
      { required: true, message: '请输入工作内容' },
      { min: 5, message: '工作内容至少5个字符' },
      { max: 500, message: '工作内容不能超过500个字符' },
    ],
    hours: [
      { required: true, message: '请输入耗时' },
      { type: 'number', min: 0, max: 24, message: '耗时必须在0-24小时之间' },
    ],
    remaining: [{ type: 'number', min: 0, message: '剩余时间不能为负数' }],
    object: [{ max: 200, message: '对象描述不能超过200个字符' }],
    product: [{ max: 100, message: '产品名称不能超过100个字符' }],
    executor: [{ max: 50, message: '执行不能超过50个字符' }],
    project: [{ max: 100, message: '项目名称不能超过100个字符' }],
  }

  return (
    <Form
      form={form}
      layout='vertical'
      onFinish={handleSubmit}
      initialValues={{
        date: dayjs(),
        hours: 8,
        remaining: 0,
      }}
    >
      <Row gutter={16}>
        <Col xs={24} sm={12} md={8}>
          <Form.Item name='date' label='日期' rules={validateRules.date}>
            <DatePicker
              style={{ width: '100%' }}
              format='YYYY-MM-DD'
              placeholder='选择日期'
            />
          </Form.Item>
        </Col>

        <Col xs={24} sm={12} md={8}>
          <Form.Item
            name='hours'
            label='耗时（小时）'
            rules={validateRules.hours}
          >
            <InputNumber
              style={{ width: '100%' }}
              min={0}
              max={24}
              step={0.5}
              precision={1}
              placeholder='请输入耗时'
            />
          </Form.Item>
        </Col>

        <Col xs={24} sm={12} md={8}>
          <Form.Item
            name='remaining'
            label='剩余（小时）'
            rules={validateRules.remaining}
          >
            <InputNumber
              style={{ width: '100%' }}
              min={0}
              step={0.5}
              precision={1}
              placeholder='请输入剩余时间'
            />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item name='content' label='工作内容' rules={validateRules.content}>
        <TextArea
          rows={3}
          placeholder='请详细描述工作内容...'
          showCount
          maxLength={500}
        />
      </Form.Item>

      <Row gutter={16}>
        <Col xs={24} sm={12} md={8}>
          <Form.Item name='object' label='对象' rules={validateRules.object}>
            <Input placeholder='任务对象或目标' />
          </Form.Item>
        </Col>

        <Col xs={24} sm={12} md={8}>
          <Form.Item name='product' label='产品' rules={validateRules.product}>
            <Input placeholder='所属产品' />
          </Form.Item>
        </Col>

        <Col xs={24} sm={12} md={8}>
          <Form.Item
            name='executor'
            label='执行'
            rules={validateRules.executor}
          >
            <Input placeholder='执行' />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item name='project' label='项目' rules={validateRules.project}>
        <Input placeholder='所属项目' />
      </Form.Item>

      <Form.Item style={{ marginBottom: 0 }}>
        <div className='form-actions'>
          <Button
            type='default'
            onClick={() => form.resetFields()}
            disabled={loading}
          >
            重置
          </Button>
          <Button
            type='primary'
            htmlType='submit'
            icon={<PlusOutlined />}
            loading={loading}
          >
            添加工时记录
          </Button>
        </div>
      </Form.Item>
    </Form>
  )
}

export default AddWorkTime
